package edu.hut.bookshop.service.impl;

import com.github.pagehelper.PageHelper;
import edu.hut.bookshop.dao.BookMapper;
import edu.hut.bookshop.dao.FavoritesMapper;
import edu.hut.bookshop.pojo.Book;
import edu.hut.bookshop.pojo.Favorites;
import edu.hut.bookshop.service.FavoritesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class FavoritesServiceImpl implements FavoritesService {
    @Autowired
    private  FavoritesMapper favoritesMapper;
    @Autowired
    private BookMapper bookMapper;

    @Override
    public int insertFav(Integer userId,Integer jiajuId) {
        Favorites fav = new Favorites();
        fav.setUserId(userId);
        fav.setBookId(jiajuId);
        fav.setStatus(true);
        Integer rows = favoritesMapper.insertFav(fav);
        return rows;
    }


    //查询
    @Override
    public List<Book> selectByUserId(Integer userId) {
        //先通过userid查找所有在收藏表的jiajuid
        List<Integer> jiajuIds = favoritesMapper.selectByUserId(userId);
        List<Book> books = new ArrayList<>();
        //再通过jiajuid去查找商品的所有信息
       for(int i=0;i<jiajuIds.size();i++){
            books.add(bookMapper.selectByBookId(jiajuIds.get(i)));
       }
        return books;
    }

    //删除
    @Override
    public int deleteFav(Integer jiajuId) {
        return favoritesMapper.deleteFav(jiajuId);
    }

    @Override
    public List<Book> fuzzyQueryByName(Integer page, Integer limit,String bookName) {
        PageHelper.startPage(page, limit);
        List<Book> books =favoritesMapper.fuzzyQueryByName(bookName);
        return books;
    }
}
